//
//  Product_TabViewController.m
//  CMVRFForIOS
//
//  Created by HailongHan on 15/3/27.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Product_TabViewController.h"
#import "ProductListCommonResponse.h"
#import <TPKeyboardAvoidingTableView.h>
#import "ProjectData.h"
#import "GuidData.h"
#import "SearchData.h"
#import "ProductDetailViewController.h"
#import "ProductTableViewCell.h"
#import "CacheData.h"
#import "MJRefresh.h"
#import "ProductXlViewController.h"
#import "FjpgViewController.h"
#import "ProductListViewController.h"

@interface Product_TabViewController () {
    NSUInteger beginIndex;
    NSUInteger endIndex;
    BOOL showSearchTable;
}

@property (nonatomic,strong) UISearchBar *productSearchBar;
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSource;
@property (nonatomic,retain) NSMutableArray *OriginDataSource;
@property (nonatomic,copy) NSString *searchStr;

@property (nonatomic,strong) UIWebView *webView;

@end

@implementation Product_TabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
//    tapGr.cancelsTouchesInView = NO;
//    [self.view addGestureRecognizer:tapGr];
    
    [self setupWebViews];
    
//    [self initData];
//    [self setupViews];
//    [self loadData];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
}

/**
 *  初始化数据
 */
- (void)initData {
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    self.dataSource = [NSMutableArray new];
    self.OriginDataSource = [NSMutableArray new];
    showSearchTable = NO;
}

#pragma mark - 初始化视图
- (void)setupWebViews{
    self.webView = [[UIWebView alloc] initWithFrame:kScreen_Bounds];
    NSString *secretAgent = [self.webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    if ([secretAgent rangeOfString:@"OutesBrowser"].location == NSNotFound) {
        secretAgent = [NSString stringWithFormat:@"%@ SHP-APP",secretAgent];
        
        NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"OutesBrowser", @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    }
    
    self.webView.height -= kStatus_Navigation_Height + kTab_Bar_Height;
    if (iPhone_X) {
        self.webView.height -= KIphoneX_Adjust_Height;
    }
    self.webView.delegate = self;
    
    self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    self.webView.scalesPageToFit = YES;
    self.webView.multipleTouchEnabled = YES;
    self.webView.userInteractionEnabled = YES;
    
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://at.outes.com/pro/"]];
    [self.view addSubview: self.webView];
    [MBProgressHUD showMessage:@"数据加载中..." toView:self.view];
    [self.webView loadRequest:request];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [MBProgressHUD hideHUDForView:self.view];
    self.webView.height = [UIView frameWithOutNavTab].size.height;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
}


- (void)setupViews{
    self.title = @"产品";
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(backTop)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"back_top"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        if (showSearchTable) {
            [self refreshData];
        }
        else {
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (showSearchTable) {
            [self loadMoreData];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    
//    [self.view addSubview:self.tableView];
}

- (void)backTop {
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] showMainViewController];
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    //先从缓存里读取
//    self.OriginDataSource = [[CacheData sharedDataBase] getArrayResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andModel:NSStringFromClass([SearchData class])];
//    if (self.OriginDataSource != nil && self.OriginDataSource.count > 0) {
//        [self.dataSource addObjectsFromArray:self.OriginDataSource];
//        //刷新数据
//        [self.tableView reloadData];
//    }
//    else {
//        
//    }
    [self loadProductVersion];
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self searchProducts:self.searchStr];
}

- (void)loadMoreData {
    //下级公司发布的意见
    if (self.dataSource.count == 0) {
        return;
    }
    // 马上进入刷新状态
    [self.tableView.mj_footer beginRefreshing];
    beginIndex = self.dataSource.count;
    endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
    [self searchProducts:self.searchStr];
}


- (void)loadProductVersion {
    [HttpClient getWithUrl:HTTP_GET_ALL_PRODUCTS token:[[AccountManager manager]token] paramDic:nil resultClass:[SearchData class] success:^(SearchData *obj) {
        if (obj != nil) {
            
            //判断有木有版本升级
            NSString *lastDBVersion = [[NSUserDefaults standardUserDefaults] objectForKey:ProductDBVersionKey];
            if ([lastDBVersion intValue] != obj.getProductDbVersionResult) {
                //存储这次版本号
                [Tools saveKeyValues:[NSString stringWithFormat:@"%d", obj.getProductDbVersionResult] forKey:ProductDBVersionKey];
                //版本
                //重新加载数据
//                [self loadAllProducts];
            }
            else {
                //已经从缓存里读取了数据
//                self.OriginDataSource = [[CacheData sharedDataBase] getArrayResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andModel:NSStringFromClass([SearchData class])];
//                if (self.OriginDataSource != nil && self.OriginDataSource.count > 0) {
//
//                }
//                else {
//                    //没有从缓存里读出来，那就再加载数据把
//                    [self loadAllProducts];
//                }
            }
            
        }
    } failure:^(NSError *error) {
        CMLog(@"获取产品失败：%@", error);
    }];
}

//- (void)loadAllProducts {
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    [param setValue:[NSNumber numberWithInt:0] forKey:@"icd"];
//    
//    [HttpClient getWithUrl:HTTP_GET_ALL_PRODUCTS token:[[AccountManager manager]token] paramDic:param resultClass:[SearchData class] success:^(SearchData *obj) {
//        if (obj.getAllProductsResult != nil && obj.getAllProductsResult.count > 0) {
//            [[CacheData sharedDataBase] setResponseWithUserName:[[AccountManager manager] token] andUrl:HTTP_GET_ALL_PRODUCTS andParam:@"" andDateTime:@"2015-12-31 00:00:00" andResponse:obj.getAllProductsResult];
//            [self.OriginDataSource addObjectsFromArray:obj.getAllProductsResult];
//            [self.dataSource addObjectsFromArray:obj.getAllProductsResult];
//            [self.tableView reloadData];
//        }
//    } failure:^(NSError *error) {
//        CMLog(@"获取产品失败：%@", error);
//    }];
//}

- (void)searchProducts:(NSString*)keyword {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInt:0] forKey:@"icd"];
    [param setValue:[NSNumber numberWithInteger:beginIndex] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:endIndex] forKey:@"ei"];
    [param setValue:keyword forKey:@"kw"];
    showSearchTable = NO;
    
    [HttpClient getWithUrl:HTTP_GET_SEARCH_PRODUCTS token:[[AccountManager manager]token] paramDic:param resultClass:[SearchData class] success:^(SearchData *obj) {
        showSearchTable = YES;
        if (beginIndex == 0) {
            [self.tableView.mj_header endRefreshing];
            [self.dataSource removeAllObjects];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
        if (obj.searchResult != nil && obj.searchResult.count > 0) {
            [self.dataSource addObjectsFromArray:obj.searchResult];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (beginIndex == 0) {
            [self.tableView.mj_header endRefreshing];
        }
        else {
            [self.tableView.mj_footer endRefreshing];
        }
        CMLog(@"获取产品失败：%@", error);
    }];
}

- (void)loadProductSeries:(NSString *)tag {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:tag forKey:@"tag"];
    [param setValue:[NSNumber numberWithInt:1] forKey:@"ac"]; //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
    
    [HttpClient getWithUrl:HTTP_GET_PRODUCT_SERIES token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
    
}


#pragma mark - 事件的响应
/**
 *  called when text changes (including clear)
 *
 *  @param searchBar  <#searchBar description#>
 *  @param searchText <#searchText description#>
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchBar.text.length == 0) {
        //加载所有的产品
        showSearchTable = NO;
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:self.OriginDataSource];
        [self.tableView reloadData];
    }
}
/**
 *  用户编辑时的响应
 *
 *  @param searchBar 控件的ID
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
}

/**
 *  called when keyboard search button
 *
 *  @param searchBar <#searchBar description#>
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
    NSLog(@"%@", searchBar.text);
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
    self.searchStr = [[NSString alloc] initWithString:searchBar.text];
    [self searchProducts:searchBar.text];
}




#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!showSearchTable) {
        return 5;
    }
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!showSearchTable) {
        static NSString *identifier = @"type_Cell_Identifier";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
        cell.textLabel.font = [UIFont systemFontOfSize:kListTitleFontSize];
        if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"product_snj"];
            cell.textLabel.text = @"风机盘管";
        }else if (indexPath.row == 0){
            cell.imageView.image = [UIImage imageNamed:@"product_syj"];
            cell.textLabel.text = @"主机";
        }
        else if (indexPath.row == 4){
            cell.imageView.image = [UIImage imageNamed:@"product_dr"];
            cell.textLabel.text = @"净水器";
        }
        else if (indexPath.row == 3){
            cell.imageView.image = [UIImage imageNamed:@"product_rsq"];
            cell.textLabel.text = @"空气能热水器";
        }
        else if (indexPath.row == 2){
            cell.imageView.image = [UIImage imageNamed:@"product_xfxt"];
            cell.textLabel.text = @"新风系统";
        }
        return cell;
    }
    static NSString *identifier = @"ProductCell";
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
    [cell setProductTitle:item.xh andXl:item.xl andXs:item.xs];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!showSearchTable) {
        return 44;
    }
    static NSString *identifier = @"ProductCell";
    ProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
    BOOL hasXl = NO;
    if (![item.xl isKindOfClass:[NSNull class]] && ![item.xl isEmpty]) {
        hasXl = YES;
    }
    BOOL hasXs = NO;
    if (![item.xs isKindOfClass:[NSNull class]] && ![item.xs isEmpty]) {
        hasXs = YES;
    }
    return [cell getHeight:hasXl andXs:hasXs];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!showSearchTable) {
        //跳转到列表页面
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        ProductXlViewController *view = [ProductXlViewController new];
        view.title = cell.textLabel.text;
        switch (indexPath.row) {
            case 1:
                //室内机
            {
//                FjpgViewController *vc = [FjpgViewController new];
//                [self.navigationController pushViewController:vc animated:YES];
//                return;
                view.product_type = MACHINE_TAG_FOR_FCU;
                break;
            }
                break;
            case 0:
                //主机机
                view.product_type = MACHINE_TAG_FOR_MAIN;
                break;
            case 4:
                //轻型商用空调
                view.product_type = MACHINE_TAG_FOR_WATER_CLEANER;
                break;
            case 3:
                //空气能热水机
                view.product_type = MACHINE_TAG_FOR_KQNRSJ;
                break;
            case 2:
                //新风系统
                view.product_type = MACHINE_TAG_FOR_QRJHQ;
                break;
            default:
                break;
        }
        [self.navigationController pushViewController:view animated:YES];
        return;
    } else {
        SearchData *item = [self.dataSource objectAtIndex:indexPath.row];
        ProductDetailViewController *view = [ProductDetailViewController new];
        view.product_type = item.tag;
        view.equip_id = item.guidId;
        [self.navigationController pushViewController:view animated:YES];
    }
   
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


#pragma mark - 触碰屏幕隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if ([self.productSearchBar isFirstResponder]) {
        [self.productSearchBar resignFirstResponder];
    }
    
}

@end
